// Copyright 2012 Jay Young. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview
 *
 * Provides several functions that prepare the output folder.
 */

var logger = require('ringo/logging').getLogger('Prep'),
    fs = require('fs');

/**
 * An instance of Class<RLoader>.  Used to locate the CSS files when everything
 * is bundled into a JAR.
 *
 * @type {Class<RLoader}
 */
var loader = (new Packages.RLoader()).getClass();


/**
 * CSS file names.
 *
 * @type {Array.<string>}
 */
var cssFiles = [
  'class.css',
  'common.css',
  'enum.css',
  'file.css',
  'typedef.css'
];


/**
 * Create the given directory and set up the directory structure for the
 * output.  This includes copying the CSS files into the html/ subfolder.
 *
 * The directory structure will be:
 * outputPath/
 *   <intermediate .json files>
 *   html/
 *     <HTML doc pages>
 *     styles/
 *       <CSS files>
 *
 * @param {string} ConfigParser The config object for this program run.
 *    Requires that "config.outputPath" and "config.verbose" already be set.
 */
exports.prepare = function(config) {
  var outputPath = config.outputPath;

  checkOutputPathExists(outputPath, config.verbose);
  copyCSS(outputPath);
};


/**
 * Make sure that the output HTML path exists.
 * @param {string} outputPath The folder to ensure exists.  The output path
 *    must end in a trailing slash.
 * @param {boolean} verbose Log lots or little?
 */
function checkOutputPathExists(outputPath, verbose) {
  // Ensure that this directory exists.  If it doesn't, later parts of the
  // program will throw when trying to write into it.
  var htmlOutputPath = outputPath + 'html/',
      cssOutputPath = htmlOutputPath + 'styles/';

  if (! fs.isDirectory(cssOutputPath)) {
    logger.info('Creating output path and sub-directories.');
    fs.makeTree(cssOutputPath);
  }
}


/**
 * Copy CSS files into the output folder.  The html/styles/ subfolder must
 * already exist.
 *
 * @param {string} outputPath The top-level output folder.  The output path must
 *    end in a trailing slash.
 */
function copyCSS(outputPath) {
  var cssOutputPath = outputPath + 'html/styles/';

  for (var i = 0, len = cssFiles.length; i < len; ++i) {
    var cssPath = 'styles/' + cssFiles[i];

    var jarStream = loader.getResourceAsStream(cssPath),
        from = new java.io.BufferedInputStream(jarStream),

        output = new java.io.FileOutputStream(cssOutputPath + cssFiles[i]),
        to = new java.io.BufferedOutputStream(output);

    var {ByteArray} = require('binary'),
        buffer = new ByteArray(2048);

    try {
      var count = from.read(buffer);
      while (count > -1) {
        to.write(buffer, 0, count);
        count = from.read(buffer);
      }
    }
    catch (e) {
      logger.error('Error while copying CSS files to output path: ' + e);
    }
    finally {
      from.close();
      to.close();
    }
  }
}
